package com.ErpCoreWeb.View;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CView;
import com.ErpCoreModel.UI.CViewFilter;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class SingleViewInfo4
 */
@WebServlet("/SingleViewInfo4")
public class SingleViewInfo4 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CUser m_User = null;
    public CView m_View = null;
    public UUID m_Catalog_id = Util.GetEmptyUUID();
    boolean m_bIsNew = false;   
    public CTable m_Table = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SingleViewInfo4() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
            	response.getWriter().print("请重新登录！");
            	response.getWriter().close();
            	//response.getWriter().print("url:../Login.jsp");
				//response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User = (CUser)request.getSession().getAttribute("User");
		
		String id = request.getParameter("id");
        if (!Global.IsNullParameter(id))
        {
            m_View = (CView)Global.GetCtx(this.getServletContext()).getViewMgr().Find(Util.GetUUID(id));
        }
        else
        {
            m_bIsNew = true;
            if (request.getSession().getAttribute("NewView") == null)
            {
            	try {
                	response.getWriter().print("时间超时！");
                	response.getWriter().close();
					//response.getWriter().print("url:SingleViewInfo1.aspx?id=" + request.getParameter("id") + "&catalog_id=" + m_Catalog_id.toString());
					//response.sendRedirect("SingleViewInfo1.jsp?id=" + request.getParameter("id") + "&catalog_id=" + request.getParameter("catalog_id"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                return ;
            }
            else
            {
            	Map<UUID, CView> sortObj = (Map<UUID, CView>)request.getSession().getAttribute("NewView");
                m_View =(CView) sortObj.values().toArray()[0];
            }
        }
        
        m_Table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(m_View.getFW_Table_id());
        
        String catalog_id = request.getParameter("catalog_id");
        if (!Global.IsNullParameter(catalog_id))
        {
            m_Catalog_id = Util.GetUUID(catalog_id);
        }
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
        	GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Delete"))
        {
        	Delete();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
        	request.getSession().setAttribute("NewView", null);
            return ;
        }
        else if (Action.equalsIgnoreCase("Add"))
        {
        	Add();
            return ;
        }
	}

    void GetData()
    {
        String sData = "";
        int iCount = 0;

        List<CBaseObject> lstObj = m_View.getViewFilterMgr().GetList();
        List<CViewFilter> sortObj = new ArrayList<CViewFilter>();
        for (CBaseObject obj : lstObj)
        {
            CViewFilter ViewFilter = (CViewFilter)obj;
            sortObj.add(ViewFilter);
        }
        Collections.sort(sortObj, new Comparator<CBaseObject>() {  
            public int compare(CBaseObject o1, CBaseObject o2) {  
                int result = o1.m_arrNewVal.get("idx").IntVal - o2.m_arrNewVal.get("idx").IntVal;  
                return result;  
            }  
        }); 

        for (CViewFilter ViewFilter : sortObj)
        {
            CColumn col = (CColumn)m_Table.getColumnMgr().Find(ViewFilter.getFW_Column_id());
            if (col == null)
                continue;
            
            sData += String.format("{ \"id\": \"%s\",\"AndOr\":\"%s\",\"Column\":\"%s\",\"Sign\":\"%s\", \"Val\":\"%s\" },"
                    , ViewFilter.getId().toString()
                    , ViewFilter.getAndOr().equalsIgnoreCase("and")?"与":"或"
                    , col.getName()
                    , ViewFilter.GetSignName()
                    , ViewFilter.getVal());


            iCount++;
        }

        if (sData.endsWith(","))
			sData = sData.substring(0, sData.length() - 1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void Delete()
    {
    	String delid = request.getParameter("delid");
        if (Global.IsNullParameter(delid))
        {
        	try {
				response.getWriter().print("请选择一项！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
        
        m_View.getViewFilterMgr().Delete(Util.GetUUID(delid));

    }
    void PostData()
    {
        if (m_bIsNew)
        {
        	m_View.setCreator ( m_User.getId());
            m_View.setUpdated ( new Date(System.currentTimeMillis()));
            Global.GetCtx(this.getServletContext()).getViewMgr().AddNew(m_View);
        }
        else
        {
        	 m_View.setUpdator ( m_User.getId());
             m_View.setUpdated ( new Date(System.currentTimeMillis()));
             Global.GetCtx(this.getServletContext()).getViewMgr().Update(m_View);
        }
        if (!Global.GetCtx(this.getServletContext()).getViewMgr().Save(true))
        {
			try {
				response.getWriter().print("保存失败！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
    	request.getSession().setAttribute("NewView", null);
    }
   

    void Add()
    {
		String txtVal = request.getParameter("txtVal");
		String cbAndOr = request.getParameter("cbAndOr");
		String cbColumn = request.getParameter("cbColumn");
		String cbSign = request.getParameter("cbSign");
		
        CViewFilter Filter = new CViewFilter();
        Filter.Ctx = Global.GetCtx(this.getServletContext());
        Filter.setUI_View_id ( m_View.getId());
        Filter.setAndOr ( cbAndOr);
        Filter.setFW_Table_id ( m_Table.getId());
        Filter.setFW_Column_id (Util.GetUUID(cbColumn));
        if(cbSign.equals(">"))
        	Filter.setSign (0);
        else if(cbSign.equals("<"))
        	Filter.setSign (1);
        else if(cbSign.equals(">="))
        	Filter.setSign (2);
        else if(cbSign.equals("<="))
        	Filter.setSign (3);
        else if(cbSign.equals("!="))
        	Filter.setSign (4);
        else if(cbSign.equals("like"))
        	Filter.setSign (5);
        Filter.setVal ( txtVal);
        Filter.setIdx ( m_View.getViewFilterMgr().GetList().size());

        m_View.getViewFilterMgr().AddNew(Filter);

        
    }

}
